package ru.spbau.bytecode.projectobserver;

import java.io.File;
import java.io.IOException;
import java.util.Set;

import ru.spbau.bytecode.graph.CompositeVertex;
import ru.spbau.bytecode.graph.Edge;
import ru.spbau.bytecode.graph.Graph;
import ru.spbau.bytecode.reader.BytecodeReader;

public class ClassesObserver extends ProjectObserver {
	
	@Override
	public String getName() {
		return "Classes";
	}
	
	@Override
	protected void findDependencies(File[] classFiles,
			File projectDirectory, Graph graph, File currentDirectory) throws IOException {
		for (File f : classFiles) {
			BytecodeReader reader = new BytecodeReader();
			reader.run(f.getAbsolutePath());
			
			Set<String> classes = reader.getClasses();
			String currentClass = reader.getCurrentClass();
			
			String[] currentClassParts = currentClass.split("[.]");
			
			CompositeVertex v1 =
				new CompositeVertex(currentClassParts[currentClassParts.length - 1]);
			graph.addVertex(v1);

			for (String s: classes) {
				String parts[] = s.split("[.]");
				
				// if this class is not from this project
				if (parts.length < 4 ||
						!parts[0].equals(currentClassParts[0]) || 
						!parts[1].equals(currentClassParts[1]) ||
						!parts[2].equals(currentClassParts[2])) {
					continue;
				}
				
				String targetClassName = parts[parts.length - 1];
				CompositeVertex v2 = new CompositeVertex(targetClassName);
				graph.addVertex(v2);
				graph.addEdge(new Edge(v1, v2));
			}
		}
	}

}